﻿Imports Microsoft.VisualBasic

Namespace MyApp
    Namespace Network
        Public Class Google

            Private db As mDB = mDB.GetDB

            Public Property oauth2 As WebApi.Oauth.Oauth2

            Public Sub New()

            End Sub

            Public Sub New(oauth2 As WebApi.Oauth.Oauth2)
                Me.oauth2 = oauth2

            End Sub

            Public Function RedirectAuth() As String

                Return oauth2.GetDialog("https://accounts.google.com/o/oauth2/auth",
                    "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile") 'profile

            End Function



            Public Sub AddLogin(code As String)
                Dim CurrUser = MyApp.GetUser(False)

                'oauth2.access_token = access_token
                oauth2.code = code

                oauth2.ConfirmingIdentity("https://accounts.google.com/o/oauth2/token", "POST", "JSON")


                Dim tc = New WebApi.Google.GoogleClient(oauth2)

                Dim CurrPeople = tc.GetPeople("me")
                Dim Acc = Me.UpdateAccountPeople(CurrPeople)

                '--------------------------------------------
                ' creo account_auth

                Dim AccAuth = Acc.Account_Auth ' CurrUser.tab_acc Tab_UserAccount.BY.User_Account.Account_Id(acc.Id).Limit(1).ToObj
                If AccAuth Is Nothing Then
                    AccAuth = New mDB.Account_Auth
                    db.TAB.Account_Auth.InsertOnSubmit(AccAuth)
                End If

                AccAuth.Account_Id = Acc.Id
                AccAuth.Network_Id = MyApp.Network.AccType.GOOGLE_PEOPLE
                AccAuth.Oauth_Consumer_Key = oauth2.client_id
                AccAuth.Oauth_Consumer_Secret = oauth2.client_secret
                AccAuth.Oauth_Token = oauth2.access_token
                AccAuth.Oauth_Token_Secret = oauth2.refresh_token

                AccAuth.Error_Account_Last_Date = Date.MinValue
                AccAuth.Error_Account_Count = 0
                AccAuth.Disabled = 0

                '--------------------------------------------
                ' creo user_account
                Dim UserAcc = CurrUser.Tab_User_Account(Acc.Id).ToObj
                If UserAcc Is Nothing Then
                    UserAcc = New mDB.User_Account
                    db.TAB.User_Account.InsertOnSubmit(UserAcc)
                End If

                UserAcc.User_Id = CurrUser.Id
                UserAcc.Account_Id = Acc.Id

                db.SubmitChanges()

            End Sub
            Public Sub RefreshLogin()

                'oauth2.access_token = access_token

                oauth2.RefreshIdentity("https://accounts.google.com/o/oauth2/token", "POST", "JSON")

                Dim tc = New WebApi.Google.GoogleClient(oauth2)

                Dim CurrPeople = tc.GetPeople("me")
                Dim Acc = Me.UpdateAccountPeople(CurrPeople)

                '--------------------------------------------
                ' creo account_auth

                Dim AccAuth = Acc.Account_Auth
                AccAuth.Oauth_Token = oauth2.access_token

                AccAuth.Error_Account_Last_Date = Date.MinValue
                AccAuth.Error_Account_Count = 0
                AccAuth.Disabled = 0

            End Sub


            Public Function UpdateAccountPeople(tu As WebApi.Google.People) As mDB.Account

                '--------------------------------------------
                ' creo account
                Dim Acc = mDB.Account.GetForUpdate(tu.id, AccType.GOOGLE_PEOPLE)


                Acc.Fullname = tu.displayName
                Acc.Username = ""
                Acc.Avatar = tu.image.url
                'If tu.location IsNot Nothing Then
                '    Acc.Location = tu.location.name
                'End If
                'Acc.Description = MyApp.ToUTF8DB(tu.headline)
                Acc.Url = tu.url

                Acc.Account_Add_Info.Profile_Update = Now
                'Acc.Account_Update.Follower_Count = tu.numconnections

                db.SubmitChanges()

                Return Acc

            End Function

            Public Function DownloadAccountFriends(Acc As mDB.Account) As Boolean
                Dim tc = New WebApi.Google.GoogleClient(oauth2)

                'prendo l'ulmito cursor
                Dim Cursor = Acc.Account_Update.Friend_Last_Code


                Do
                    'scarico i friends
                    Dim Foll = tc.GetPeopleList(Acc.Account_Code, Cursor)

                    MyApp.WriteProcLog(SF("(tab)(tab)update Friends: {1}", Acc.Fullname, Foll.items.Count), Task.TaskType.UPDATE_ACCOUNTS)

                    For Each f In Foll.items

                        Acc.AddAccountLink(mDB._Account_Link.Type.FRIENDS, f.id, AccType.GOOGLE_PEOPLE)
                        Me.UpdateAccountPeople(f)

                    Next
                    Cursor = Foll.nextPageToken

                    '-------------------------------------------------------------
                    'aggiona il link_update
                    Acc.Account_Update.Friend_Last_Code = Cursor

                    db.SubmitChanges()

                Loop Until Cursor = ""

                Return Cursor = ""




            End Function

#Region "QUERY"

            Public Sub DownloadQueryPosts(q As mDB.Query, Mode As mDB.Query.UpdateModeType)
                'Const NumPostFindEnd = 50
                'Const NumPostToDownload = 2000

                Dim tc = New WebApi.Google.GoogleClient(Me.oauth2)

                Dim EndDownload = False
                Dim ContinuePrevDownload = False
                Dim Since = ""
                Dim Until = ""
                Dim ResultType = ""

                Dim PostCount = 0


                'imposto la query
                Dim query As String = q.Query
                Dim geocode As String = ""
                Dim Lang As String = ""



                Do Until EndDownload

                    'Dim tweets = tc.GetSearch(query, Since_id, Max_id, ResultType, geocode, Lang)
                    Dim tweets = tc.GetactivitiesSearch(query)

                    For Each t In tweets.items

                        Me.UpdateQueryPost(q, t)
                        PostCount += 1

                    Next

                    MyApp.WriteProcLog(SF("(tab)(tab)(tab)update query: {0} - '{1}'", PostCount, q.Query), Task.TaskType.UPDATE_QUERY)


                    EndDownload = True

                    'If tweets.data.Count > 0 Then
                    '    'Dim par = HttpUtility.ParseQueryString(tweets.paging.next)
                    '    'Max_id = par("until")
                    '    Until = Utils.Conv.ToTimeStamp(tweets.data.Last.created_time.ToUniversalTime)
                    'End If

                    'q.Post_Last_Code = SF("{0},{1}", Since, Until)
                    'db.SubmitChanges()


                    'If tweets.data.Count < NumPostFindEnd Or PostCount > NumPostToDownload Then
                    '    EndDownload = True
                    'End If

                    'If EndDownload And ContinuePrevDownload Then
                    '    ContinuePrevDownload = False
                    '    EndDownload = False
                    '    PostCount = 0
                    '    Since = q.GetLastPostDateUniversalTimeStamp
                    '    Until = ""
                    'End If


                Loop

                If EndDownload Then
                    q.Post_Download_Count = PostCount
                    q.Post_Last_Code = ""
                    db.SubmitChanges()
                End If

            End Sub

            Public Function UpdateQueryPost(query As mDB.Query, t As WebApi.Google.activity) As mDB._Query_Post

                'aggiorna post
                'Dim Post = db.TAB.Query_Post.BY.Query_Post.Query_Id(query.Id, t.id).ToObj
                Dim Post = query._Tab_Query_Post.BY._Query_Post._Post_Code(t.id).ToObj
                'Dim Post = Acc._Tab_Account_Post.BY._Account_Post._Post_Code(t.id).ToObj

                If Post Is Nothing Then
                    Post = New mDB._Query_Post
                    db.InsertOnSubmit(query.ArchivePost.Table_Name, Post)
                End If

                Post.Query_Id = query.Id
                Post.Post_Code = t.id

                If t.verb.ToUpper = "POST" Then
                    Post.Post_Text = t.object.content
                Else
                    Post.Post_Text = t.annotation
                End If

                Post.Post_Text = HttpUtility.HtmlDecode(Post.Post_Text)
                Post.Post_Text = Regex.Replace(Post.Post_Text, "<[^>]*>", String.Empty, RegexOptions.IgnoreCase)

                Post.Account_Username = t.actor.displayName
                If t.object.attachments.Count > 0 Then
                    If t.object.attachments(0).image IsNot Nothing Then
                        Post.Image_Url = t.object.attachments(0).image.url
                    End If
                End If

                Post.Pubb_Date = t.published


                db.SubmitChanges()

                Return Post

            End Function

#End Region
        End Class


    End Namespace
End Namespace
